package org.bookstore.dao.impl;
import java.util.*;
import org.bookstore.model.*;
import org.bookstore.dao.*;
import org.hibernate.*;
public class BookDAO extends BaseDAO implements IBookDAO{
	public List getNewBook(){
		Session session=getSession();
		Query query=session.createQuery("from Book b");
		query.setFirstResult(0);
		query.setMaxResults(5);
		List books=query.list();
		session.close();
		return books;
	}

	public List getBookByCatalogidPaging(Integer catalogid,int currentPage,int pageSize){
		Session session=getSession();
		Query query=session.createQuery("from Book b where b.catalog.catalogid=?");
		query.setParameter(0, catalogid);
		int startRow=(currentPage-1)*pageSize;
		query.setFirstResult(startRow); 
		query.setMaxResults(pageSize);
		List books=query.list();
		session.close();
		return books;
	}
	
	public int getTotalByCatalog(Integer catalogid){
		try{
			Session session=getSession();
			Transaction ts=session.beginTransaction();
			Query query=session.createQuery("from Book b where b.catalog.catalogid=?");
			query.setParameter(0, catalogid);
			List books=query.list();
			ts.commit();
			session.close();
			return books.size();
		}catch(Exception e){
			e.printStackTrace();
			return 0;
		}
	}

	public List getRequiredBookByName(String name){
		try{
			Session session=getSession();
			Transaction ts=session.beginTransaction();
			Query query=session.createQuery("from Book where bookname like ?");
			query.setParameter(0, "%"+name+"%");
			List books=query.list();
			ts.commit();
			session.close();
			return books;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	public Book getBookById(Integer bookid){
		Session session=getSession();
		Transaction ts=session.beginTransaction();
		return (Book)session.get(Book.class, bookid);
	}
}
